const express = require('express');
const app = express();
const db = require('./dataBase/db');
const _ = require('underscore');
const server = require('http').createServer(app);
const io = require('socket.io')(8082);
const bodyParser = require('body-parser');
const tools = require('./utils/tools');
const verify = require('./src/verify');

let userList = {
    "test": true
};

onlineUsers = 0;

app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', true);
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    // res.header('Content-Type', 'application/json;charset=utf-8');
    next();
})

// 聊天socket部分
io.on('connection', socket => {
    socket.on('chatInit', async data => {


        let token = data.token;
        let res = await verify(token);
        if (!res.status) {
            socket.emit('chatInit', { status: false, content: '信息发送失败,token验证失败' });
            return;
        }

        id = res.userData.userId;
        socket.id = id; //为socket.id赋值
        console.log(`${socket.id}连接了回来!`);

        console.log('当前socket的id列表:');
        for (item in io.sockets.sockets) {
            console.log(io.sockets.sockets[item].id);
        }

        if (userList[id]) {
            socket.emit('chatInit', { status: false, content: '重复登陆!' })
            return;
        }

        if (userList[id] == void 0) {
            onlineUsers++;
            userList[id] = true;
            socket.emit('chatInit', { status: true, content: 'socket-id初始化成功' })
        }
    });
    socket.on('chat', async data => {
        // data: {
        //     token,
        //     content,
        //     chatId
        // }


        //验证token
        let token = data.token;
        let res = await verify(token);
        if (!res.status) {
            socket.emit('isSend', { status: false, content: '信息发送失败,token验证失败' });
            return;
        }

        //获取该chat数据
        let userData = res.userData;
        let chatId = data.chatId;
        let chatRes = await db.Chats.findOne({ id: chatId });
        if (!chatRes) {
            socket.emit('isSend', { status: false, content: '信息发送失败,聊天已被删除' });
            return;
        }

        //发送聊天数据(先存入数据库)
        let chatdata = {
            userId: userData.userId,
            date: tools.getNowDate(),
            content: data.content
        }
        try {
            await db.Chats.updateOne({ id: chatId }, { '$push': { record: { $each: [chatdata], $position: 0 } }, latestTime: chatdata.date });
        } catch (err) {
            socket.emit('isSend', { status: false, content: '信息发送失败,数据库存入失败' });
            return;
        }

        // console.log(userList);

        chatdata.chatId = chatId;
        //遍历聊天用户表，给每个用户发送socket报文
        socket.emit('isSend', { status: true, content: "信息发送成功!", data: chatdata })

        chatRes.userList.forEach(item => {
            if (item.userId == userData.userId) {
                return;
            } else {
                let toSocket = _.findWhere(io.sockets.sockets, { id: item.userId });
                if (toSocket) {
                    console.log(`(${userData.userId})向(${item.userId})发送了' + ${chatdata.content}`);
                    toSocket.emit('chat', chatdata);
                }
            }
        })
    })

    //注销
    socket.on('userCancel', data => {
        userList[data.userId] = null;
    });

    socket.on('disconnect', () => {
        console.log(socket.id + '断开了连接');
        userList[socket.id] = null;
        socket.id = null;
        socket = null;
        console.log('丢弃成功!');
    })
})

//引入接口
const public = require('./src/public');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 正常接口部分
app.use('/static', express.static('static'));
app.use('/public', public);



server.listen(8081, () => console.log('server is running on the port 8081!'));